import { store } from "@/store";
import { usePermissionStoreHook } from "@/store/modules/permission";

import AuthAPI, { type checkSms } from "@/api/auth";
import PermissionAPI from "@/api/commonPermission/permission";

import { setToken, clearToken } from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
    const loginInfo = useStorage<any>("loginInfo", {} as any); // 用户登录信息
    const userInfo = useStorage<any>("userInfo", {} as any); // 用户信息
    const userPerm = useStorage<any>("userPerm", [] as any); // 用户权限信息

    /**
     * 验证验证码
     *
     * @param {checkSms}
     * @returns
     */
    function checkSms(loginData: checkSms) {
        return new Promise<void>((resolve, reject) => {
            AuthAPI.checkSms(loginData)
                .then((data) => {
                    const { token, user } = data;
                    setToken(token.token_type + " " + token.access_token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx 设置token
                    Object.assign(loginInfo.value, { ...user }); // 设置登陆人信息
                    resolve(data);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    /**
     * 获取用户所有公共信息信息
     * @param
     * @returns
     */
    function getAllCommonUserInfo(loginData: checkSms) {
        return Promise.all([
            PermissionAPI.getUserInfo().then((data) => {
                Object.assign(userInfo.value, data); // 设置用户信息
                return data;
            }),
            PermissionAPI.getBtnPerm().then((data) => {
                Object.assign(userPerm.value, data); // 设置权限信息
                return data;
            }),
        ]).catch((error) => {
            throw error;
        });
    }

    /**
     * 登出
     */
    function logout() {
        return new Promise<void>((resolve, reject) => {
            AuthAPI.logout()
                .then(() => {
                    clearUserSession();
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    /**
     * 清理用户会话
     *
     * @returns
     */
    function clearUserSession() {
        return new Promise<void>((resolve) => {
            clearToken();
            usePermissionStoreHook().resetRouter();

            // loginInfo.value = [];
            // userInfo.value = [];
            // userPerm.value = [];
            resolve();
        });
    }

    return {
        userInfo,
        checkSms,
        getAllCommonUserInfo,
        logout,
        clearUserSession,
    };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
    return useUserStore(store);
}
